<template>
  <div class="sample">
    <el-button
      v-if="!readOnly"
      icon="el-icon-plus"
      style="margin-bottom: 8px"
      type="primary"
      @click="addSample"
      >新增样品</el-button
    >
    <el-button
      v-if="!readOnly"
      style="margin-bottom: 8px"
      type="primary"
      @click="batchChoiceDetectionItem"
      >批量选择检测项目</el-button
    >
    <div>
      <el-row
        v-for="(item, index) in sampleList"
        :key="index"
        style="margin-bottom: 10px"
      >
        <el-card class="box-card">
          <el-row>
            <div v-if="!readOnly" style="float: left">
              <el-checkbox v-model="checked[index]"></el-checkbox>
            </div>
            <div v-if="!readOnly" style="float: right">
              <img
                src="../../img/copy.png"
                alt=""
                @click="copy(index)"
              />&nbsp;&nbsp;
              <img
                v-if="item.samplingDataState != 1"
                src="../../img/delete.png"
                alt=""
                @click="del(index)"
              />
            </div>
          </el-row>
          <br />

          <el-form
            ref="formData"
            class="sample-form"
            :model="item"
            label-width="130px"
            status-icon
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="原始编号：">
                  <el-input
                    v-model="item.originalSampleNumber"
                    style="width: 200px"
                    :disabled="systemType === 'cdc' || readOnly"
                  />
                  <!-- <span style="color: red; padding-left: 3px">*</span> -->
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="样品编号：">
                  <el-input
                    v-model="item.sampleNum"
                    style="width: 200px"
                    :disabled="item.samplingDataState == 1 || readOnly"
                    @change="changeSampleNum(index)"
                  />
                  <!-- <span style="color: red; padding-left: 3px">*</span> -->
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="姓名：">
                  <el-input
                    v-model="item.detectedName"
                    :disabled="readOnly"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="性别：">
                  <el-radio-group v-model="item.sex" :disabled="readOnly">
                    <el-radio
                      v-for="(sItem, sIndex) in sexLixt"
                      :key="sIndex"
                      :label="sItem.value"
                      >{{ sItem.name }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="年龄：">
                  <el-input
                    v-model="item.age"
                    :disabled="readOnly"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="送检医师：">
                  <el-input
                    v-model="item.referralPhysician"
                    :disabled="readOnly"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="标本种类：">
                  <el-input
                    v-model="item.specimenType"
                    :disabled="readOnly"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="样品名称：">
                  <el-input
                    v-model="item.sampleName"
                    :disabled="readOnly"
                    style="width: 200px; float: left"
                  />
                  <el-cascader
                    v-if="!readOnly"
                    ref="cascader"
                    v-model="item.cascaderSampleName"
                    :disabled="readOnly"
                    class="sample-form_cascader"
                    style="width: 10px; margin-left: -47px; float: left"
                    :props="{ value: 'id', label: 'label', emitPath: false }"
                    :options="sampleCategoryList"
                    :filter-method="filterMethod(item)"
                    @change="changeCascader(item, index)"
                  ></el-cascader>
                  <div
                    v-if="!readOnly"
                    style="color: red; float: left; padding-left: 3px"
                  >
                    *
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="标注商标：">
                  <el-input
                    v-model="item.brand"
                    :disabled="readOnly"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="样品份数：">
                  <el-input
                    v-model="item.sampleCount"
                    :disabled="readOnly"
                    style="width: 200px"
                    oninput="value=value.replace(/[^\d]/g,'')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="单份容量：">
                  <el-input
                    v-model="item.capacity"
                    :disabled="readOnly"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="生产日期/批号：">
                  <el-input
                    v-model="item.batchNum"
                    :disabled="readOnly"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="生产厂家：">
                  <el-input
                    v-model="item.manufacturer"
                    :disabled="readOnly"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="受检单位：">
                  <el-input
                    v-model="item.inspectedAddress"
                    :disabled="readOnly"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="采样地点：">
                  <el-input
                    v-model="item.samplingPosition"
                    :disabled="readOnly"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="样品形态：">
                  <el-input
                    v-model="item.sampleShape"
                    :disabled="readOnly"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="样品等级：">
                  <el-input
                    v-model="item.sampleGrade"
                    :disabled="readOnly"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="保存条件：">
                  <el-input
                    v-model="item.storageConditions"
                    :disabled="readOnly"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="保存时间：">
                  <el-input
                    v-model="item.saveTime"
                    :disabled="readOnly"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="样品处理意见：">
                  <el-input
                    v-model="item.sampleHandlingComments"
                    :disabled="readOnly"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-button
                v-if="!readOnly"
                icon="el-icon-choiceDetectionItem"
                type="primary"
                plain
                @click="addDetection(index)"
                >选择检测项目</el-button
              >
            </el-row>
            <el-row>
              <el-table
                ref="table"
                :data="item.tableData"
                border
                style="width: 100%"
                :span-method="objectSpanMethod"
              >
                <el-table-column prop="detectionItemName" label="检测项目" />
                <el-table-column prop="methodStandard" label="方法标准编号">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.methodStandard"
                      :disabled="readOnly"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="nationalStandardNum"
                  label="产品标准编号"
                >
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.nationalStandardNum"
                      :disabled="readOnly"
                    ></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-form>
        </el-card>
      </el-row>
    </div>
    <ChoiceDetectionItemDialog
      ref="ChoiceDetectionItemDialog"
      v-model="dialogDetectionItem"
      :generate-button-state="true"
      @DetectionItemClose="detectionItemClose"
    />
  </div>
</template>
<script>
import {
  GetSampleNum,
  // GetSampleNumByNewNum,
} from "../../api/EntrustManage/EntrustSampleDetection.js";
import {getSampleTree} from "@/ModuleSysBusiness/api/DetectionItemManage/SysBusinessSampleCategory.js";
import { arrayRecursion } from "@/utils/Helper";

export default {
  name: "EntrustGeoptahyDetection",
  components: {},
  props: {
    readOnly: {
      type: Boolean,
      default: false,
    },
    systemType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      sexLixt: [{ value: 1, name: "男" }, { value: 0, name: "女" }],
      cascaderSampleName: "",
      sampleCategoryLis: [],
      batchChoiceState: false,
      checked: [],
      dialogDetectionItem: false,
      // 用于记录选择检测项目的下标
      detectionIndex: -1,
      sampleList: [],
      spanArres: [],
      poes: 0,
      sampleCategoryIdList: [],
    };
  },
  watch: {},
  created() {
    this.getSampleList();
  },
  methods: {
    // 修改样品编号要对比之前生成的编号看是否相同，不同修改状态
    changeSampleNum(index) {
      if (
        this.sampleList[index].sampleNum !== null &&
        this.sampleList[index].sampleNum !== ""
      ) {
        if (
          this.sampleList[index].sampleNum !==
          this.sampleList[index].generateNum
        ) {
          this.sampleList[index].numUseState = 0;
        }
      }
    },

    arrayRecursion,
    filterMethod(a, b, item) { },
    changeCascader(item, index) {
      var nodesInfo = this.$refs.cascader[index].getCheckedNodes();
      if (nodesInfo.length > 0) {
        this.sampleList[index].sampleName = nodesInfo[0].pathLabels.join("/");
        this.sampleList[index].sampleShape = nodesInfo[0].data.shape;
        this.sampleList[index].capacity = nodesInfo[0].data.capacity;
        this.sampleList[index].capacityUnit = nodesInfo[0].data.capacityUnit;
      }
    },
    getSampleList() {
      var obj = {};
      getSampleTree(obj)
        .then((res) => {
          this.sampleCategoryList = this.arrayRecursion(res.data);
        })
        .catch();
    },
    // 批量选择检测项目
    batchChoiceDetectionItem() {
      if (this.sampleList.length === 0 || this.sampleList === null) {
        this.$message.warning("请先新增样品");
        return false;
      }

      if (this.checked.length === 0 || this.checked === null) {
        this.$message.warning("请选择样品数据");
        return false;
      }

      this.batchChoiceState = true;
      this.dialogDetectionItem = true;
    },
    // 判断输入内容
    blurTexts(e) {
      const boolean = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      if (!boolean) {
        this.$message.warning("请输入正整数");
        e.target.value = "";
      }
    },
    // 对于需要合并的行做标记
    getSpanArr(data) {
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArres.push(1);
          this.poes = this.spanArres.length - 1;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].methodStandardName === data[i - 1].methodStandardName) {
            this.spanArres[this.poes] += 1;
            this.spanArres.push(0);
          } else {
            this.spanArres.push(1);
            this.poes = this.spanArres.length - 1;
          }
        }
      }
    },
    // 合并行或列
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 2) {
        const _row = this.spanArres[rowIndex];
        return {
          rowspan: _row,
          colspan: 1,
        };
      }
    },
    // 选择检测项目
    addDetection(index) {
      this.detectionIndex = index;
      if (
        this.sampleList[this.detectionIndex].detectionItemData !== undefined &&
        this.sampleList[this.detectionIndex].detectionItemData.length > 0 &&
        this.sampleList[this.detectionIndex].detectionItemData !== null
      ) {
        this.$refs.ChoiceDetectionItemDialog.sampleDeteciontItemData.push({
          detectionItemData: JSON.parse(
            JSON.stringify(
              this.sampleList[this.detectionIndex].detectionItemData
            )
          ),
          sysBusinessSampleCategoryId:
            this.sampleList[this.detectionIndex].detectionItemData[0]
              .sysBusinessSampleCategoryId,
        });
        // 选择的检测项目表赋值检测项目
        this.$refs.ChoiceDetectionItemDialog.selectedTableData = JSON.parse(
          JSON.stringify(this.sampleList[this.detectionIndex].detectionItemData)
        );
      }
      this.dialogDetectionItem = true;
    },
    // 组成检测项目显示的表格
    detectionTableData(index) {
      // 需要保存检测项目id 因为后面更改表格内容需要根据主键来修改新增的信息
      // 获取sampleList检测项目中的判定标准
      var methodStandardName = [];
      this.sampleList[index].detectionItemData.forEach((item) => {
        methodStandardName.push({
          detectionItemId: item.id,
          methodStandardName: item.methodStandardName,
          methodStandard: item.methodStandard,
          nationalStandardNum: item.nationalStandardNum,
        });
      });

      // 对象根据方法标准编号和产品标准编号去重
      var arr1 = [];
      var arr2 = [];

      for (let i = 0; i < methodStandardName.length; i++) {
        if (
          !arr1.includes(
            methodStandardName[i].methodStandard +
            "-" +
            methodStandardName[i].methodStandardName
          )
        ) {
          arr1.push(
            methodStandardName[i].methodStandard +
            "-" +
            methodStandardName[i].methodStandardName
          );
          arr2.push({
            methodStandard: methodStandardName[i].methodStandard,
            methodStandardName: methodStandardName[i].methodStandardName,
          });
        }
      }

      methodStandardName = arr2;

      this.sampleList[index].tableData = [];
      // 表格赋值
      methodStandardName.forEach((element) => {
        this.sampleList[index].tableData.push({
          methodStandard: element.methodStandard,
          nationalStandardNum: element.nationalStandardNum,
          methodStandardName: element.methodStandardName,
        });

        var detectionItemName = [];
        var productStandardList = [];
        var detectionItemIdList = [];
        this.sampleList[index].detectionItemData.forEach((item) => {
          if (
            item.methodStandardName === element.methodStandardName &&
            item.methodStandard === element.methodStandard
          ) {
            detectionItemIdList.push(item.id);
            detectionItemName.push(item.detectionItemName);
            if (
              item.nationalStandardNum !== null &&
              item.nationalStandardNum !== ""
            ) {
              productStandardList.push(item.nationalStandardNum);
            }
          }
        });
        // 检测项目名称去重
        detectionItemName = [...new Set(detectionItemName)];
        productStandardList = [...new Set(productStandardList)];
        detectionItemIdList = [...new Set(detectionItemIdList)];
        this.sampleList[index].tableData[
          this.sampleList[index].tableData.length - 1
        ].detectionItemName = detectionItemName.join(",");
        this.sampleList[index].tableData[
          this.sampleList[index].tableData.length - 1
        ].nationalStandardNum = productStandardList.join(",");
        this.sampleList[index].tableData[
          this.sampleList[index].tableData.length - 1
        ].detectionItemIdList = detectionItemIdList;
      });
      this.getSpanArr(this.sampleList[index].tableData);
    },
    // 关闭选择检测项目弹框
    detectionItemClose(data, generateFileState, fileData) {
      var rowIndex = this.detectionIndex;
      // 批量选择检测项目
      if (this.batchChoiceState) {
        for (let i = 0; i < this.checked.length; i++) {
          // 如果样品复选框按钮选中
          if (this.checked[i]) {
            this.choiceDetectionItem(i, data, generateFileState, fileData);
            this.detectionTableData(i);
          }
        }
      } else {
        this.choiceDetectionItem(
          this.detectionIndex,
          data,
          generateFileState,
          fileData
        );
        this.detectionTableData(this.detectionIndex);
        this.detectionIndex = -1;
      }

      // 获取样品类别id
      this.sampleCategoryIdList = [];
      for (let i = 0; i < this.sampleList.length; i++) {
        for (let o = 0; o < this.sampleList[i].detectionItemData.length; o++) {
          this.sampleCategoryIdList.push(
            this.sampleList[i].detectionItemData[o].sysBusinessSampleCategoryId
          );
        }
      }

      this.$emit("sampleCategoryChange", this.sampleCategoryIdList);
      if (this.systemType === "cdc") {
        var sampleCategoryIdList = [];
        sampleCategoryIdList.push(data[0].sysBusinessSampleCategoryId);

        this.getSampleNum(sampleCategoryIdList, rowIndex);
      }
    },

    // 选择的检测项目存入值
    choiceDetectionItem(detectionIndex, data, generateFileState, fileData) {
      this.sampleList[detectionIndex].generateFileState = generateFileState;
      if (fileData !== null && fileData !== undefined) {
        this.sampleList[detectionIndex].FileName = fileData.fileName;
      }
      if (
        this.sampleList[detectionIndex].detectionItemData === undefined ||
        this.sampleList[detectionIndex].detectionItemData === null
      ) {
        this.sampleList[detectionIndex].detectionItemData = [];
      }
      this.sampleList[detectionIndex].detectionItemData = [];
      data.forEach((item) => {
        item.detectionItemData.forEach((items) => {
          this.sampleList[detectionIndex].detectionItemData.push(items);
        });
      });
    },

    // 复制
    copy(index) {
      this.sampleList.push(JSON.parse(JSON.stringify(this.sampleList[index])));
      this.sampleList[this.sampleList.length - 1].samplingDataState = 0;
      // this.sampleList[this.sampleList.length - 1].numUseState = 0;
      this.checked.push(false);
      if (this.systemType === "cdc") {
        var sampleCategoryIdList = [];

        for (
          let o = 0;
          o <
          this.sampleList[this.sampleList.length - 1].detectionItemData.length;
          o++
        ) {
          sampleCategoryIdList.push(
            this.sampleList[this.sampleList.length - 1].detectionItemData[o]
              .sysBusinessSampleCategoryId
          );
        }

        this.getSampleNum(sampleCategoryIdList, -1);
      }
    },
    // 获取编号
    getSampleNum(sampleCategoryIdList, rowIndex) {
      GetSampleNum({ sampleCategoryIdList: sampleCategoryIdList })
        .then((res) => {
          if (res.data.code === 200) {
            if (rowIndex !== -1) {
              this.sampleList[rowIndex].numUseState = 1;
              this.sampleList[rowIndex].sampleNum = res.data.data;
              this.sampleList[rowIndex].generateNum = res.data.data;
            } else {
              this.sampleList[this.sampleList.length - 1].numUseState = 1;
              this.sampleList[this.sampleList.length - 1].sampleNum =
                res.data.data;
              this.sampleList[this.sampleList.length - 1].generateNum =
                res.data.data;
            }
          } else {
            this.$message(res.data.msg);
          }
        })
        .catch(() => { });
    },
    // 新增样品
    addSample() {
      this.sampleList.push({
        id: 0,
        sampleName: "",
        sampleNum: "",
        generateNum: "",
        brand: "",
        manufacturer: "",
        sampleShape: "",
        capacity: "",
        capacityUnit: "",
        sampleCount: 1,
        numUseState: 0,
        samplingDataState: 0, // 用于判断是否为选择采样带出的数据
        generateFileState: 1, // 是否生成附件默认1不生成
        tableData: [],
        detectionItemData: [],
        entrustDetections: [],
        cascaderSampleName: ''
      });
      this.checked.push(false);
      if (this.systemType === "cdc") {
        this.getSampleNum(null, -1);
      }
    },
    // 删除样品
    del(index) {
      this.sampleList.splice(index, 1);
      this.checked.splice(index, 1);
    },
  },
};
</script>
<style scoped>
.inputContent {
  width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.el-icon-choiceDetectionItem {
  background: url("../../img/choiceDetectionItem.png") center no-repeat;
  font-size: 16px;

  /* background-size: cover;*/
}
.el-icon-choiceDetectionItem:before {
  font-size: 16px;
  visibility: hidden;
  content: "\e611";
}
.el-input__suffix {
  right: -28px;
}
</style>
<style lang="scss" scoped>
.sample {
  &-form {
    &_cascade {
      width: 10px;
      margin-left: -47px !important;
    }
  }
}
</style>
